package com.fred.colorpicker

import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import com.fred.colorpicker.listener.ColorPickerListener
import com.fred.colorpicker.listener.GrayColorListener
import com.fred.colorpicker.listener.ColorWheelListener
import com.fred.colorpicker.indicator.ColorWheelIndicator
import com.fred.colorpicker.indicator.RectColorWheelIndicator
import com.fred.colorpicker.indicator.RingColorWheelIndicator

class ColorPickerView:LinearLayout, ColorWheelListener, GrayColorListener {

    private val colorWheelView by lazy {
        ColorWheelView(context)
    }

    private val graySeekBar by lazy {
        GraySeekBar(context)
    }

    var listener:ColorPickerListener? = null

    constructor(context: Context?) : super(context){init()}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs){init()}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) :
            super(context, attrs, defStyleAttr){init()}
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) :
            super(context, attrs, defStyleAttr, defStyleRes){init()}

    fun setIndicator(one: ColorWheelIndicator, two: ColorWheelIndicator? = null){
        colorWheelView.setSelector(one,two)
        graySeekBar.setIndicator(one)
    }

    //ColorWheelListener
    override fun onSelectColor(color: Int, saturation: Float, brightness: Float) {
        graySeekBar.setColor(color,saturation, brightness)
    }

    override fun onSelectorChange(one: ColorWheelIndicator?, two: ColorWheelIndicator?) {
        if (one?.isSelected == true){
            graySeekBar.setIndicator(one)
        }else if (two?.isSelected == true){
            graySeekBar.setIndicator(two)
        }
    }

    //GrayColorListener
    override fun onSelectorColor(color: Int) {
        if (colorWheelView.oneIndicator?.isSelected == true){
            listener?.onOneColorChange(color)
        }else if (colorWheelView.twoIndicator?.isSelected == true) {
            listener?.onTwoColorChange(color)
        }
    }

    fun setColorPickerListener(listener: ColorPickerListener?){
        this.listener = listener
    }

    private fun init(){
        orientation = VERTICAL
        val layoutParams = LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT)
        val selector = RingColorWheelIndicator(context)
        colorWheelView.setSelector(selector,RectColorWheelIndicator(context))
        graySeekBar.setIndicator(selector)
        colorWheelView.colorWheelListener = this
        graySeekBar.selectorColorListener = this
        addView(colorWheelView,layoutParams)
        layoutParams.topMargin = context.dip(8F).toInt()
        addView(graySeekBar,layoutParams)
    }



}